package com.wooshow.base.local;

import java.sql.Connection;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;

/**
 * This class is used to overwrite JdbcDaoSupport in Spring, in order to add two batchUpdate methods to optimize performance.
 * Seems that Spring's batch update do not have the tasks done in a batch way.
 */
public class LocalJdbcDaoSupport extends org.springframework.jdbc.core.support.JdbcDaoSupport {

	public int[] localBatchUpdate(String[] sql) throws Exception {
		Connection conn = getConnection(); // get connection from spring
		boolean autoCommit = conn.getAutoCommit();
		conn.setAutoCommit(false);
		Statement statement = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
		for (int i = 0; i < sql.length; i++) {
			statement.addBatch(sql[i]);
		}
		int[] counts = statement.executeBatch();
		conn.commit();
		conn.setAutoCommit(autoCommit);
		conn = null;
		return counts;
	}

	public int[] localBatchUpdate(String sql, BatchPreparedStatementSetter bpss) throws Exception {
		Connection conn = getConnection(); // get connection from spring
		boolean autoCommit = conn.getAutoCommit();
		conn.setAutoCommit(false);
		PreparedStatement ps = conn.prepareStatement(sql);
		for (int i = 0; i < bpss.getBatchSize(); i++) {
			bpss.setValues(ps, i);
			ps.addBatch();
		}
		int[] counts = ps.executeBatch();
		conn.commit();
		conn.setAutoCommit(autoCommit);
		conn = null;
		return counts;
	}

}
